#!/bin/bash

ipaddr=`ifconfig eth0 | grep "inet addr" | cut -d ':' -f2 | awk '{print $1}'`
if [ -n "$ipaddr" ]
then 
    exit 0;
fi
if [ -e /home/Config/wire.json ]
then
      linkmode=$(jq -r '.linkmode' /home/Config/wire.json)
      if [ $linkmode = "dhcp" ]; then
         ps -fe|grep ifplugd |grep -v grep
         if [ $? -eq 0 ]
         then
               pkill -9 ifplugd 
               sleep 1s
         fi
         ps -fe|grep dhcpc_eth |grep -v grep
         if [ $? -eq 0 ]
         then
               pkill -9 dhcpc_eth 
               sleep 1s
         fi
         /usr/sbin/ifplugd -I -i eth0 -r /usr/share/script/monitorWired.sh
         /sbin/dhcpc_eth -b -i eth0 -p /var/run/udhcpc.pid -R

      else
         localipaddr=$(jq -r '.ipaddr' /home/Config/wire.json)
         netmaskaddr=$(jq -r '.netmask' /home/Config/wire.json)
         localgateway=$(jq -r '.gateway' /home/Config/wire.json)
         ps -fe|grep ifplugd |grep -v grep
         if [ $? -eq 0 ]
         then
               pkill -9 ifplugd
               sleep 1s
         fi
         ps -fe|grep dhcpc_eth |grep -v grep
         if [ $? -eq 0 ]
         then
               pkill -9 dhcpc_eth
               sleep 1s
         fi

         ifconfig eth0 $localipaddr netmask $netmaskaddr
         route add default gw $localgateway dev eth0 metric 20
         pkill -9 ntpd
         /usr/sbin/ntpd &
      fi
fi
